package com.op.studyingliteapp.fragment.notif;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.op.studyingliteapp.R;
import com.op.studyingliteapp.activity.NotifDetailActivity;
import com.op.studyingliteapp.bean.CourseNotifBean;
import com.op.studyingliteapp.common.Common;
import com.op.studyingliteapp.common.NotifUrl;
import com.op.studyingliteapp.database.dao.CourseNotifDao;
import com.op.util.StringUtils;
import com.op.util.asynctask.HttpPostTask;
import com.op.util.asynctask.OnTaskProcessListener;
import com.op.util.pullrefresh.RefreshableView;
import com.op.util.pullrefresh.RefreshableView.PullToRefreshListener;

/**
 * 
 * @author handsome
 *
 */
public class NotifFragment extends Fragment {
	private View view;
	ListView notifListView;
	RefreshableView refreshableView;
	NotifListAdapter mAdapter;
	private String getCourseUserId, getCourseId;
	private ArrayList<NotifCellData> list = new ArrayList<NotifCellData>();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_notif, container, false);

		SharedPreferences preferences = getActivity().getSharedPreferences(
				"StudyingLite", Context.MODE_PRIVATE);
		getCourseUserId = preferences.getString(Common.Prefs.USER_ID, "");
		getCourseId = preferences.getString(Common.Prefs.COURSE_ID, "");
		downLoadData();

		notifListView = (ListView) view.findViewById(R.id.notif_listview);
		mAdapter = new NotifListAdapter(getActivity(), list);
		notifListView.setAdapter(mAdapter);
		notifListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(getActivity(),
						NotifDetailActivity.class);
				intent.putExtra("position", position);

				startActivity(intent);
			}
		});
		
		
		/**
		 * 下拉刷新
		 */
		refreshableView = (RefreshableView) view
				.findViewById(R.id.refreshable_view);
		refreshableView.setOnRefreshListener(new PullToRefreshListener() {

			@Override
			public void onRefresh() {
				try {

					Thread.sleep(1000);
				} catch (Exception e) {
					e.printStackTrace();
				}
				/**
				 * 另起线程进行刷新
				 */
				Thread action = new Thread(new Runnable() {

					@Override
					public void run() {
						Looper.prepare();
						downLoadData();
						Looper.loop();
					}
				});
				action.start();
				refreshableView.finishRefreshing();
			}

		}, 0);
		
		
		return view;
	}

	
	@Override
	public void onResume() {
		super.onResume();
	}

	/**
	 * 发送courseId从网上下拉通知json
	 */
	public void downLoadData() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("courseId", getCourseId));
		HttpPostTask task = new HttpPostTask(getActivity(),
				NotifUrl.GET_COURSE_NOTIF_AND_OWNER_BY_COURSE_ID, params);
		task.setTaskListener(new OnTaskProcessListener() {
			@Override
			public void prepare() {
			}

			@Override
			public void completed(String result) {
				if (StringUtils.isEmptyOrStringNull(result)) {
					getDataFromDatabase();
				} else {
					Log.i("", "通知" + result);
					// 有网络登陆时
					analytical(result);
					getDataFromDatabase();
				}
				mAdapter.notifyDataSetChanged();

			}

		});
		task.execute();// 执行结束，圈转完
	}

	/**
	 * 从数据库获取数据 // 从数据库提取课程通知内容
	 */
	public void getDataFromDatabase() {

		CourseNotifDao courseNotifDao = new CourseNotifDao(getActivity(),
				getCourseUserId);
		List<CourseNotifBean> courseNotif = courseNotifDao
				.getNotifByCourseId(getCourseId);
		list.clear();
		// 获取通知
		for (int i = 0; i < courseNotif.size(); i++) {
			String title = courseNotif.get(i).getTitle();
			String time = courseNotif.get(i).getCreateTime();
			String context = courseNotif.get(i).getContent();
			String name = courseNotif.get(i).getUserBean().getName();
			String image = courseNotif.get(i).getUserBean().getImageUrl();
			// String courseNotifId = courseNotif.get(i).getId();
			list.add(new NotifCellData(image, name, title, context, time));
		}

	}

	/**
	 * 解析json，并存入数据库
	 */
	public void analytical(String result) {
		// 判断得到的数据是否为null
		if (!StringUtils.isEmptyOrStringNull(result)) {
			try {
				JSONObject jsonobjectresult = new JSONObject(result);
				String message = jsonobjectresult.getString("message");
				if (message.equals("Success")) {
					CourseNotifDao courseNotifDao = new CourseNotifDao(
							getActivity(), getCourseUserId);
					// 清空数据库
					courseNotifDao.empty();
					JSONObject resultMap = jsonobjectresult
							.getJSONObject("resultMap");
					JSONArray courseNotifList = resultMap
							.getJSONArray("CourseNotifAndOwner");
					for (int i = 0; i < courseNotifList.length(); i++) {
						JSONObject courseNotif = new JSONObject();
						courseNotif = courseNotifList.getJSONObject(i);

						// 将JsonObject存入本地数据库
						CourseNotifBean courseNotifBean = new CourseNotifBean();
						courseNotifBean.fillAttributeByJson(courseNotif);
						courseNotifDao.insertOrUpdate(courseNotifBean);
					}

				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 发送notifId从网上下拉通知具体内容和发布人的具体信息json
	 */
	public void downContentLoadData(String notifId) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("notifId", notifId));
		HttpPostTask task = new HttpPostTask(getActivity(),
				NotifUrl.GET_COURSE_NOTIF_AND_OWNER_BY_NOTIF_ID, params);
		task.setTaskListener(new OnTaskProcessListener() {
			@Override
			public void prepare() {
			}

			@Override
			public void completed(String result) {
				if (StringUtils.isEmptyOrStringNull(result)) {
					getDataFromDatabase();
				} else {
					// 有网络登陆时
					analytical(result);
					getDataFromDatabase();
				}
				mAdapter.notifyDataSetChanged();

			}

		});
		task.execute();
	}


}
